package com.cloud.websocket.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhaoyangfu - 2020/7/22 17:49
 */
@Slf4j
public class WsSessionManager {

    private final static ConcurrentHashMap<String, WebSocketSession> SESSION_MAP = new ConcurrentHashMap<>();

    public static void add(String key, WebSocketSession session) {
        SESSION_MAP.put(key, session);
    }

    public static WebSocketSession remove(String key) {
        return SESSION_MAP.remove(key);
    }

    public static void close(String key) {
        WebSocketSession session = SESSION_MAP.remove(key);
        if (session != null) {
            try {
                session.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    public static void push(WebSocketMessage<?> message) {
        SESSION_MAP.values().forEach(session -> {
            try {
                if (session != null && session.isOpen()) session.sendMessage(message);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        });
    }

    public static WebSocketSession session(String key) {
        return SESSION_MAP.get(key);
    }
}
